﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
///Basket 的摘要说明
/// </summary>
[Serializable]
public class Basket
{
    public List<Selection> items;
	public Basket()
	{

        items = new List<Selection>();
	}


    public static void ClearBasket()
    {
        HttpContext.Current.Session["UserBasket"] = new Basket();

    }
    public static Basket GetActiveBasket()
    {
        Basket basketObj;

        if (HttpContext.Current.Session["UserBasket"] != null)
        {
            basketObj = (Basket)HttpContext.Current.Session["UserBasket"];
        }
        else
        {
            basketObj = new Basket();
            HttpContext.Current.Session["UserBasket"] = basketObj;
        }

        return basketObj;
    }


    public void Add2Basket(Selection purchase)
    {
        Selection existing = FindExistingItem(purchase);

        if (existing == null)
        {
            int newID = 0;

            if (this.items.Count == 0)
                newID = 1;
            else
                newID = this.items.Max(p => p.BasketItemID) + 1;

            purchase.BasketItemID = newID;
            items.Add(purchase);
        }
       
       
    }

    private Selection FindExistingItem(Selection purchase)
    {
        Selection returnVar = null;

        Selection found;
        bool theSame = false;

        foreach (Selection x in items)
        {
            theSame = true;

            if (x.ProductNum != purchase.ProductNum)
                theSame = false;

           
            if (theSame)
            {
                returnVar = x;
                break;
            }
        }

        if (theSame == false)
            found = null;
        else
        {
            returnVar.BuyNum += purchase.BuyNum;
            found = returnVar;
        }
        return found;
    }

    public Selection GetItem(int basketItemID)
    {
        return items.FirstOrDefault(p => p.BasketItemID == basketItemID);
    }

    public List<Selection> GetItems()
    {
        return this.items;
    }

    public void RemoveFromBasket(int basketItemID)
    {
      
        var item = items.FirstOrDefault(p => p.BasketItemID == basketItemID);
        items.Remove(item);
       
    }

}